package com.hzzftech.watchdog.busi.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.hzzftech.watchdog.busi.core.executor.starter.KettleEnvironmentStarter;
import com.hzzftech.watchdog.busi.domain.KtWarnMsg;
import com.hzzftech.watchdog.busi.objs.WatchdogPageInfo;
import com.hzzftech.watchdog.busi.service.IKtDispatcherService;
import com.hzzftech.watchdog.busi.utils.PageInfoUtils;
import com.hzzftech.watchdog.common.config.KtWatchdogConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hzzftech.watchdog.common.annotation.Log;
import com.hzzftech.watchdog.common.enums.BusinessType;
import com.hzzftech.watchdog.busi.domain.RJob;
import com.hzzftech.watchdog.busi.service.IRJobService;
import com.hzzftech.watchdog.common.core.controller.BaseController;
import com.hzzftech.watchdog.common.core.domain.AjaxResult;
import com.hzzftech.watchdog.common.utils.poi.ExcelUtil;
import com.hzzftech.watchdog.common.core.page.TableDataInfo;

/**
 * 数据库资源库_jobController
 * 
 * @author kt-watchdog
 * @date 2022-01-27
 */
@Controller
@RequestMapping("/busi/JOB")
public class RJobController extends BaseController
{
    private String prefix = "busi/RJOB";

    @Autowired
    private IRJobService rJobService;

    @Autowired
    private IKtDispatcherService ktDispatcherService;

    @RequiresPermissions("busi:JOB:view")
    @GetMapping()
    public String JOB()
    {
        return prefix + "/JOB";
    }


    @RequiresPermissions("busi:JOB:view")
    @GetMapping("/select")
    public String JOBSelect()
    {
        return prefix + "/JOBView";
    }

    /**
     * 查询数据库资源库_job列表
     */
    @RequiresPermissions("busi:JOB:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RJob rJob)
    {
        WatchdogPageInfo info = PageInfoUtils.getInfo();
        Integer total = rJobService.selectRJobTotal(rJob);
        if (total > 0) {
            List<RJob> list = rJobService.selectRJobList(rJob, info.getPgNum(), info.getPgSize(), info.getOrderBy());
            return PageInfoUtils.getDataTable(list, total);
        } else {
            return PageInfoUtils.getDataTable(new ArrayList<>(0), 0);
        }
    }

    /**
     * 删除数据库资源库_job
     */
    @RequiresPermissions("busi:JOB:remove")
    @Log(title = "数据库资源库_job", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        int delCount = 0;
        try {
            for (String id : ids.split(",")) {
                repository.deleteJob(new LongObjectId(Long.parseLong(id)));
                delCount ++;
            }
        } catch (Exception e) {
            logger.error("删除失败", e);
        }
        return toAjax(delCount);
    }

    /**
     * 导出 JOB xml
     */
    @RequiresPermissions("busi:JOB:export")
    @Log(title = "kettle运行提醒信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RJob job)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        FileOutputStream out = null;
        try {
            JobMeta jobMeta = repository.loadJob(new LongObjectId(job.getIdJob()), "");
            String xml = jobMeta.getXML();
            String fileName = jobMeta.getName()+".kjb";
            String downloadPath = KtWatchdogConfig.getDownloadPath() +fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(downloadPath);
            out.write(xml.getBytes());

            return AjaxResult.success(fileName);
        } catch (Exception e) {
            logger.error("导出JOB异常", e);
            return AjaxResult.error();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("导出JOB异常", e);
                }
            }
        }
    }
}
